import requests
import hashlib
import logging
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from wxauto import WeChat
import time
import matplotlib.font_manager as fm

# Configure basic logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')


def generate_signature(app_secret, params):
    params_with_limit = params.copy()
    sorted_params = {k: v for k, v in sorted(params_with_limit.items()) if v is not None}
    param_string = "#".join([f"{k}={v}" for k, v in sorted_params.items()])
    to_encrypt = f"{app_secret}#{param_string}"
    hashed_value = hashlib.sha256(to_encrypt.encode()).hexdigest()
    return hashed_value


def request_api(base_url, api_endpoint, app_id, app_secret, data):
    try:
        signature = generate_signature(app_secret, data)
        url = f"{base_url}{api_endpoint}"
        headers = {
            'APP_ID': app_id,
            'TSINGLEY-SIGN': signature,
            'Content-Type': 'application/json'
        }

        logging.debug(f"Sending request to URL: {url}")
        logging.debug(f"Request headers: {headers}")
        logging.debug(f"Request payload: {data}")

        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # Raises HTTPError for bad responses
        logging.debug(f"Response received: {response.text}")
        return response.json()  # Return JSON response
    except requests.RequestException as e:
        logging.error(f"HTTP Request failed: {e}")
        return None


def extract_temperature_data(response):
    temperature_data = {'SV': [], 'PV': []}
    for item in response.get("data", []):
        if item['name'] == 'SV':
            temperature_data['SV'].append(float(item['value']))
        elif item['name'] == 'PV':
            temperature_data['PV'].append(float(item['value']))
    return temperature_data


def plot_temperature_data(app_id, app_secret, base_url, api_endpoint):
    # 获取当前时间
    current_time = datetime.now()
    previous_hour = current_time - timedelta(hours=1)
    beginTime = previous_hour.replace(minute=0, second=10, microsecond=0)
    endTime = previous_hour.replace(minute=59, second=0, microsecond=0)
    # 将时间格式化为字符串
    query = {
        "beginTime": beginTime.strftime('%Y-%m-%d %H:%M:%S'),
        "endTime": endTime.strftime('%Y-%m-%d %H:%M:%S'),
        "fields": "SV,PV",
        "teamId": "",
        "uuid": "",
    }

    data = request_api(base_url, api_endpoint, app_id, app_secret, query)
    if data and 'datas' in data and 'list' in data['datas']:
        filtered_data = [entry for entry in data['datas']['list'] if entry['SV'] != 'null' and entry['PV'] != 'null']
        if filtered_data:
            timestamps = [datetime.fromisoformat(entry['time'][:-1]) for entry in filtered_data]
            SV_values = [float(entry['SV']) for entry in filtered_data]
            PV_values = [float(entry['PV']) for entry in filtered_data]

            # 设置中文字体
            font_prop = fm.FontProperties(fname='C:/Windows/Fonts/msyh.ttc')  # 微软雅黑字体路径

            # 创建折线图
            plt.figure(figsize=(24, 8))
            plt.plot(timestamps, SV_values, label='温度设置', color='red')
            plt.plot(timestamps, PV_values, label='温度测量', color='green')
            plt.ylim(-10, 10)  # 自定义 Y 轴范围，从 -10 到 10

            # 添加标题和标签
            plt.xlabel('时间', fontproperties=font_prop)
            plt.ylabel('温度', fontproperties=font_prop)
            plt.legend(loc='upper left', prop=font_prop)
            plt.grid(color='black', linestyle='-', linewidth=0.5)
            # 设置 x 轴刻度格式为时:分:秒
            plt.gca().xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%H:%M:%S'))
            file = "SP_PV_plot.png"
            # 保存为图片
            plt.savefig(file)
            # 获取当前微信客户端
            wx = WeChat()
            # 获取会话列表
            wx.GetSessionList()
            # 向微信群发送消息并@某人
            group_name = '家族群'
            wx.ChatWith(group_name)
            at_person = '@老张'
            wx.SendMsg(f"{at_person} 请查看最新的温度数据图表：")
            wx.SendFiles(filepath=file)
    else:
        logging.error("Data format is incorrect or data is missing.")


def main():
    APP_ID = ""
    APP_SECRET = ""
    BASE_URL = ""
    API_ENDPOINT = "/open/api/device/history/list"#根据API文档来设置

    while True:
        current_time = datetime.now()
        logging.info(f"当前时间：{current_time}")

        if 9 <= current_time.hour < 23:
            if current_time.second == 0:
                logging.info("每隔一分钟发送一次")
                plot_temperature_data(APP_ID, APP_SECRET, BASE_URL, API_ENDPOINT)

            next_minute = (current_time.replace(second=0, microsecond=0) + timedelta(minutes=1))
            sleep_seconds = (next_minute - current_time).total_seconds()
            logging.info(f"计算距离下一个整点分钟的时间，并将程序休眠到那个时间点：{sleep_seconds}")
            time.sleep(sleep_seconds)
        else:
            tomorrow_9am = (current_time + timedelta(days=1)).replace(hour=9, minute=0, second=0, microsecond=0)
            sleep_seconds = (tomorrow_9am - current_time).total_seconds()
            logging.info(f"如果当前时间不在 9 点到 23 点之间，则计算距离明天早上 9 点的时间，并将程序休眠到那个时间点: {sleep_seconds}")
            time.sleep(sleep_seconds)


if __name__ == '__main__':
    main()
